import 'package:injectable/injectable.dart';
import 'package:vista/shared/services/storage_service.dart';
import 'package:vista/shared/services/auth_focus.dart';

/// 关系
/// 处理用户关注、粉丝
@lazySingleton
class RelationBond {
  final StorageService _storageService;
  final AuthFocus _authFocus;
  static const String _followsPrefix = 'follows_';
  static const String _isInitializedKey = 'relations_initialized';

  RelationBond(this._storageService, this._authFocus);

  /// 初始化默认关注关系
  /// 为现有用户创建一些互相关注的朋友关系
  Future<void> initializeDefaultRelations() async {
    final isInitialized = await _storageService.retrieveBool(_isInitializedKey);
    if (isInitialized == true) {
      return; // 已经初始化过了
    }

    final users = await _authFocus.getUsers();
    if (users.isEmpty) {
      return;
    }

    // 创建默认的关注关系网络
    // 用户1 关注 用户2, 用户3
    // 用户2 关注 用户1, 用户4 (与用户1互相关注，成为朋友)
    // 用户3 关注 用户1, 用户5 (与用户1互相关注，成为朋友)
    // 用户4 关注 用户2, 用户6 (与用户2互相关注，成为朋友)
    // 用户5 关注 用户3, 用户7 (与用户3互相关注，成为朋友)
    // 用户6 关注 用户4, 用户8 (与用户4互相关注，成为朋友)
    // 用户7 关注 用户5, 用户9 (与用户5互相关注，成为朋友)
    // 用户8 关注 用户6, 用户10 (与用户6互相关注，成为朋友)
    // 用户9 关注 用户7, 用户10 (与用户7互相关注，成为朋友)
    // 用户10 关注 用户8, 用户9 (与用户8、9互相关注，成为朋友)

    final defaultRelations = <String, List<String>>{};

    if (users.isNotEmpty) {
      defaultRelations[users[0].id] = [];
      if (users.length >= 2) defaultRelations[users[0].id]!.add(users[1].id);
      if (users.length >= 3) defaultRelations[users[0].id]!.add(users[2].id);
    }

    if (users.length >= 2) {
      defaultRelations[users[1].id] = [];
      if (users.isNotEmpty) defaultRelations[users[1].id]!.add(users[0].id);
      if (users.length >= 4) defaultRelations[users[1].id]!.add(users[3].id);
    }

    if (users.length >= 3) {
      defaultRelations[users[2].id] = [];
      if (users.isNotEmpty) defaultRelations[users[2].id]!.add(users[0].id);
      if (users.length >= 5) defaultRelations[users[2].id]!.add(users[4].id);
    }

    if (users.length >= 4) {
      defaultRelations[users[3].id] = [];
      if (users.length >= 2) defaultRelations[users[3].id]!.add(users[1].id);
      if (users.length >= 6) defaultRelations[users[3].id]!.add(users[5].id);
    }

    if (users.length >= 5) {
      defaultRelations[users[4].id] = [];
      if (users.length >= 3) defaultRelations[users[4].id]!.add(users[2].id);
      if (users.length >= 7) defaultRelations[users[4].id]!.add(users[6].id);
    }

    if (users.length >= 6) {
      defaultRelations[users[5].id] = [];
      if (users.length >= 4) defaultRelations[users[5].id]!.add(users[3].id);
      if (users.length >= 8) defaultRelations[users[5].id]!.add(users[7].id);
    }

    if (users.length >= 7) {
      defaultRelations[users[6].id] = [];
      if (users.length >= 5) defaultRelations[users[6].id]!.add(users[4].id);
      if (users.length >= 9) defaultRelations[users[6].id]!.add(users[8].id);
    }

    if (users.length >= 8) {
      defaultRelations[users[7].id] = [];
      if (users.length >= 6) defaultRelations[users[7].id]!.add(users[5].id);
      if (users.length >= 10) defaultRelations[users[7].id]!.add(users[9].id);
    }

    if (users.length >= 9) {
      defaultRelations[users[8].id] = [];
      if (users.length >= 7) defaultRelations[users[8].id]!.add(users[6].id);
      if (users.length >= 10) defaultRelations[users[8].id]!.add(users[9].id);
    }

    if (users.length >= 10) {
      defaultRelations[users[9].id] = [];
      if (users.length >= 8) defaultRelations[users[9].id]!.add(users[7].id);
      if (users.length >= 9) defaultRelations[users[9].id]!.add(users[8].id);
    }

    // 保存所有关注关系
    for (final entry in defaultRelations.entries) {
      await _saveFollowsList(entry.key, entry.value);
    }

    await _storageService.persistBool(_isInitializedKey, true);
  }

  /// 保存用户的关注列表
  Future<void> _saveFollowsList(String userId, List<String> followsList) async {
    final key = '$_followsPrefix$userId';
    await _storageService.persistStringList(key, followsList);
  }

  /// 获取用户的关注列表
  Future<List<String>> getFollowsList(String userId) async {
    final key = '$_followsPrefix$userId';
    final followsList = await _storageService.retrieveStringList(key);
    return followsList ?? [];
  }

  /// 关注用户
  /// [followerId] 关注者ID
  /// [followingId] 被关注者ID
  Future<void> followUser({
    required String followerId,
    required String followingId,
  }) async {
    if (followerId == followingId) {
      throw Exception('Cannot follow yourself');
    }

    final followsList = await getFollowsList(followerId);
    if (followsList.contains(followingId)) {
      return; // 已经关注过了
    }

    followsList.add(followingId);
    await _saveFollowsList(followerId, followsList);
  }

  /// 取消关注用户
  /// [followerId] 关注者ID
  /// [followingId] 被关注者ID
  Future<void> unfollowUser({
    required String followerId,
    required String followingId,
  }) async {
    final followsList = await getFollowsList(followerId);
    if (!followsList.contains(followingId)) {
      return; // 本来就没有关注
    }

    followsList.remove(followingId);
    await _saveFollowsList(followerId, followsList);
  }

  /// 检查是否已关注
  /// [followerId] 关注者ID
  /// [followingId] 被关注者ID
  Future<bool> isFollowing({
    required String followerId,
    required String followingId,
  }) async {
    final followsList = await getFollowsList(followerId);
    return followsList.contains(followingId);
  }

  /// 获取用户的粉丝列表（关注该用户的用户ID列表）
  Future<List<String>> getFollowersList(String userId) async {
    final allUsers = await _authFocus.getUsers();
    final followers = <String>[];

    for (final user in allUsers) {
      final followsList = await getFollowsList(user.id);
      if (followsList.contains(userId)) {
        followers.add(user.id);
      }
    }

    return followers;
  }

  /// 获取朋友列表（双方互相关注的用户）
  /// [userId] 用户ID
  Future<List<String>> getFriendsList(String userId) async {
    final followsList = await getFollowsList(userId);
    final friends = <String>[];

    for (final followingId in followsList) {
      final isMutual = await isFollowing(
        followerId: followingId,
        followingId: userId,
      );
      if (isMutual) {
        friends.add(followingId);
      }
    }

    return friends;
  }

  /// 检查两个用户是否是朋友（互相关注）
  /// [userId1] 用户1的ID
  /// [userId2] 用户2的ID
  Future<bool> areFriends({
    required String userId1,
    required String userId2,
  }) async {
    final user1FollowsUser2 = await isFollowing(
      followerId: userId1,
      followingId: userId2,
    );
    final user2FollowsUser1 = await isFollowing(
      followerId: userId2,
      followingId: userId1,
    );

    return user1FollowsUser2 && user2FollowsUser1;
  }

  /// 获取关注数量
  Future<int> getFollowsCount(String userId) async {
    final followsList = await getFollowsList(userId);
    return followsList.length;
  }

  /// 获取粉丝数量
  Future<int> getFollowersCount(String userId) async {
    final followersList = await getFollowersList(userId);
    return followersList.length;
  }

  /// 获取朋友数量
  Future<int> getFriendsCount(String userId) async {
    final friendsList = await getFriendsList(userId);
    return friendsList.length;
  }

  /// 获取推荐用户列表（排除已关注和当前用户）
  /// [userId] 当前用户ID
  /// [limit] 返回数量限制
  Future<List<String>> getRecommendedUsers({
    required String userId,
    int limit = 10,
  }) async {
    final allUsers = await _authFocus.getUsers();
    final followsList = await getFollowsList(userId);
    final recommended = <String>[];

    for (final user in allUsers) {
      if (user.id != userId && !followsList.contains(user.id)) {
        recommended.add(user.id);
        if (recommended.length >= limit) {
          break;
        }
      }
    }

    return recommended;
  }
}
